package com.lipuwater.agent.ui.activity;

import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.RelativeLayout;

import com.ismartlib.ui.widget.SlidingLinearLayout;
import com.ismartlib.utils.DisplayUtil;
import com.ismartlib.utils.NetUtils;
import com.lipuwater.agent.R;
import com.lipuwater.agent.app.base.ui.BaseLayoutActivity;
import com.lipuwater.agent.http.ApiCallBack;
import com.lipuwater.agent.http.HttpConfig;
import com.lipuwater.agent.http.ResponseParams;
import com.lipuwater.agent.http.api.ApiRequestsBasis;
import com.lipuwater.agent.ui.widget.CustomEditText;
import com.lipuwater.agent.utils.onclick.NoDoubleClick;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import mehdi.sakout.fancybuttons.FancyButton;
import okhttp3.Call;

/**
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛
 * 　　　　┃　　　┃神兽保佑
 * 　　　　┃　　　┃永无BUG！
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━神兽出没━━━━━━
 * Created by  Administrator  on 2017/5/22.
 * Email:924686754@qq.com
 */
public class FindPasswordActivity extends BaseLayoutActivity {
    @Bind(R.id.layout_root)
    RelativeLayout layoutRoot;
    @Bind(R.id.layout_sliding)
    SlidingLinearLayout layoutSliding;
    @Bind(R.id.edit_phone)
    CustomEditText editPhone;
    @Bind(R.id.edit_password)
    CustomEditText editPassword;
    @Bind(R.id.edit_vcode)
    CustomEditText editVcode;
    @Bind(R.id.btn_getCode)
    FancyButton btnGetCode;
    @Bind(R.id.btn_find_password)
    FancyButton btnFindPassWord;


    private Timer mTimer;
    private int times = 60;

    private int slidingHeight;
    private int slidingState = 0;

    private NoDoubleClick mNoDoubleClick = new NoDoubleClick();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setMyContentView(R.layout.activity_find_password);
        initTitle(R.drawable.icon_aleft_white, "找回密码");
        toolbar.setBackgroundResource(R.drawable.img_title_bar);
        toolbarTitle.setTextColor(Color.parseColor("#ffffff"));
        ButterKnife.bind(this);
        slidingHeight = DisplayUtil.dip2px(FindPasswordActivity.this, 110);
        layoutRoot.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
                int screenHeight = getWindow().getDecorView().getRootView().getHeight();
                int heightDifference = screenHeight - r.bottom;
                if (heightDifference > 0 && slidingState != 1) {
                    slidingState = 1;
                    layoutSliding.ScrollToY(0, slidingHeight);
                } else if (heightDifference == 0 && slidingState != 0) {
                    slidingState = 0;
                    layoutSliding.ScrollToY(layoutSliding.getCurrY(), -slidingHeight);
                }
            }
        });
    }

    @OnClick({R.id.btn_getCode, R.id.btn_find_password})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_getCode:
                if (mNoDoubleClick.check()) return;
                String mobiles = editPhone.getText().toString();
                if (TextUtils.isEmpty(mobiles)) {
                    Toast("请输入手机号码");
                } else if (mobiles.matches("[1][3458]\\d{9}")) {
                    //请求验证码
                    getVCode();
                } else {
                    Toast("手机号码格式输入有误");
                }
                break;
            case R.id.btn_find_password:
                if (mNoDoubleClick.check()) return;
                if (editPhone.getText().toString().equals("")) {
                    Toast("请输入手机号码");
                } else if (editPassword.getText().toString().equals("")) {
                    Toast("请输入新密码");
                } else if (editVcode.getText().toString().equals("")) {
                    Toast("请输入验证码");
                } else {
                    findPassWord();
                }
                break;
        }
    }

    private void getVCode() {
        Map<String, Object> params = new HashMap<>();
        params.put("mobile", editPhone.getText().toString());
        params.put("reuseValid", 1);
        params.put("expireTime", 60);
        params.put("type", "sms");
        ApiRequestsBasis.getVCode(this, params, new ApiCallBack() {
            @Override
            public void onResponse(ResponseParams result) {
                if (result.getStatus() == HttpConfig.success) {
                    btnGetCode.setClickable(false);
                    btnGetCode.setBackgroundColor(ContextCompat.getColor(FindPasswordActivity.this, R.color.lineColor));
                    mTimer = new Timer();
                    mTimer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            runOnUiThread(new Runnable() {      // UI thread
                                @Override
                                public void run() {
                                    times--;
                                    btnGetCode.setText(times + "s");
                                    if (times == 0) {
                                        mTimer.cancel();
                                        mTimer = null;
                                        btnGetCode.setText("重新获取");
                                        btnGetCode.setClickable(true);
                                        btnGetCode.setBackgroundColor(ContextCompat.getColor(FindPasswordActivity.this, R.color.btn_color_blue_default));
                                        times = 60;
                                    }
                                }
                            });
                        }
                    }, 1000, 1000);    // timeTask
                } else {
                    Toast(result.getMessage());
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                if (NetUtils.isConnected(FindPasswordActivity.this)) {
                    Toast(getString(R.string.service_error));
                } else {
                    Toast(getString(R.string.network_fails));
                }
            }
        });
    }

    private void findPassWord() {
        btnFindPassWord.setEnabled(false);
        Map<String, Object> params = new HashMap<>();
        params.put("loginName", editPhone.getText().toString());
        params.put("password", editPassword.getText().toString());
        params.put("vcode", editVcode.getText().toString());
        ApiRequestsBasis.findPassWord(this, params, new ApiCallBack() {
            @Override
            public void onResponse(ResponseParams result) {
                btnFindPassWord.setEnabled(true);
                if (result.getStatus() == HttpConfig.success) {
                    Toast("密码重置成功");
                    finish();
                } else {
                    Toast("密码重置失败");
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                btnFindPassWord.setEnabled(true);
                if (NetUtils.isConnected(FindPasswordActivity.this)) {
                    Toast(getString(R.string.service_error));
                } else {
                    Toast(getString(R.string.network_fails));
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }


}
